package org.ftc.util;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class EncryptEngin {
	private final static String key = "abc1234567890DEF";
	
	public static String encrypt( String text )   {
        try {
        	if(text == null || text.length() == 0)
				return null;
            byte[] bytIn = text.getBytes();
            byte[] raw = key.getBytes("ASCII");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            byte[] bytOut = cipher.doFinal(bytIn);
            return byte2hex(bytOut).toLowerCase();
        } catch (Exception e) {
        	System.out.println("encrypt.." + e.toString());
        	return null;
        }
    }

	public static String decrypt(String sSrc)   {
		try {
			if(sSrc == null || sSrc.length() == 0)
				return null;
			byte[] raw = key.getBytes("ASCII");
			SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
			Cipher cipher = Cipher.getInstance("AES");
			cipher.init(Cipher.DECRYPT_MODE, skeySpec);
			byte[] encrypted1 = hex2byte(sSrc);

			byte[] original = cipher.doFinal(encrypted1);
			String originalString = new String(original);
			return originalString;
		} catch (Exception ex) {
			System.out.println("decrypt.." + ex.toString());
			return null;
		}
	}

    public static byte[] hex2byte ( String strhex ) {
        if (strhex == null) {
            return null;
        }
        int l = strhex.length();
        if (l % 2 == 1) {
            return null;
        }
        byte[] b = new byte[l / 2];
        for (int i = 0; i != l / 2; i++) {
            b[i] = (byte) Integer.parseInt(strhex.substring(i * 2, i * 2 + 2),
                    16);
        }
        return b;
    }

    public static String byte2hex ( byte[] b ) {
        String hs = "";
        String stmp = "";
        for (int n = 0; n < b.length; n++) {
            stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
            if (stmp.length() == 1) {
                hs = hs + "0" + stmp;
            } else {
                hs = hs + stmp;
            }
        }
        return hs.toUpperCase();
    } 

	public static void main(String[] args) throws Exception{

		System.out.println( EncryptEngin.decrypt("93229c6b5dab7a2769ab4b81c4a53547") );
	}
} 
